$output = "script_linux64"
$releaseDir = "../release"
$resourceDir = "resource"  # 要打包的 resource 目录

Write-Host "Building Linux binary for x86_64: $output"

# 设置为 Linux x86_64 构建环境
$env:CGO_ENABLED = "0"
$env:GOOS = "linux"
$env:GOARCH = "amd64"

try {
    # 构建二进制文件
    go build -ldflags="-s -w" -o "$output" 2>&1 | Out-String
    if ($LASTEXITCODE -eq 0) {
        Write-Host "Build succeeded: $output" -ForegroundColor Green

        # 创建临时目录来合并二进制和 resource 目录
        $tempDir = "build_temp"
        if (Test-Path -Path "$tempDir") {
            Remove-Item -Path "$tempDir" -Recurse -Force
        }
        New-Item -ItemType Directory -Path "$tempDir" | Out-Null
        
        # 创建 release 目录
        if (-Not (Test-Path -Path "$releaseDir")) {
            New-Item -ItemType Directory -Path "$releaseDir"
        }

        # 复制二进制文件到临时目录
        Move-Item -Path "$output" -Destination "$tempDir/" -Force

        # 如果存在 resource 目录，则复制进去
        if (Test-Path -Path "$resourceDir") {
            Copy-Item -Path "$resourceDir" -Destination "$tempDir/resource" -Recurse -Force
            Write-Host "Copied resource directory into package." -ForegroundColor Green
        } else {
            Write-Host "Resource directory not found, skipping." -ForegroundColor Yellow
        }

        # 打包整个临时目录
        $zipFile = "$output.zip"
        Compress-Archive -Path "$tempDir/*" -DestinationPath "$zipFile" -Force
        Write-Host "Created ZIP file: $zipFile" -ForegroundColor Green

        # 移动 ZIP 到 public/download 目录
        if (-Not (Test-Path -Path "$releaseDir")) {
            New-Item -ItemType Directory -Path "$releaseDir"
        }
        Move-Item -Path "$zipFile" -Destination "$releaseDir\" -Force
        Write-Host "Moved zip to $releaseDir" -ForegroundColor Green

        # 清理生成的中间文件
        Remove-Item -Path "$tempDir" -Recurse -Force
    } else {
        Write-Host "Build failed with exit code: $LASTEXITCODE" -ForegroundColor Red
        exit 1
    }
} catch {
    Write-Host "Exception occurred: $_" -ForegroundColor Red
    exit 1
} finally {
    Write-Host "Cleaning up..."
    $env:CGO_ENABLED = ""
    $env:GOOS = ""
    $env:GOARCH = ""
}
